package com.fx.controller;


import cn.hutool.core.date.DateUtil;
import com.fx.entity.UserInfo;
import com.fx.service.OrderInfoService;
import com.fx.service.UserInfoService;
import com.fx.util.Constant;
import com.fx.util.JWTUtil;
import com.fx.util.R;
import com.fx.util.UrlUtil;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.crypto.SHA1;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Auther: EDZ
 * @Date: 2018-5-28 14:19:
 * @Email: 你的邮箱
 * 概要说明：该类干嘛用的
 **/
@Controller
@RequestMapping("/wx")
public class WxController {
    Logger logger = LoggerFactory.getLogger(WxController.class);
    @Autowired
    WxMpService wxMpService;
    @Autowired
    WxPayService payService;
    @Autowired
    OrderInfoService orderInfoService;
    @Autowired
    UserInfoService userInfoService;

    @RequestMapping("/api/valid")
    public void wxValid(HttpServletResponse response, HttpServletRequest request) {
        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter out = null;
        String signature = request.getParameter("signature");
        String nonce = request.getParameter("nonce");
        String timestamp = request.getParameter("timestamp");
        String echoStr = request.getParameter("echostr");
        try {
            out = response.getWriter();
            if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
                // 消息签名不正确，说明不是公众平台发过来的消息
                response.getWriter().println("非法请求");
                return;
            }
            if (StringUtils.isNotBlank(echoStr)) {
                // 说明是一个仅仅用来验证的请求，回显echostr
                String echoStrOut = String.copyValueOf(echoStr.toCharArray());
                out.println(echoStrOut);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (out != null) out.flush();
            if (out != null) out.close();
        } finally {
            if (out != null) out.flush();
            if (out != null) out.close();
        }
    }

    @RequestMapping("/api/readyGetWxUserInfo")
    public String readyGetWxUserInfo(HttpServletRequest request) {
        String jumpUrl = request.getParameter("jumpUrl");
        String redirectUri = UrlUtil.getServerUrl(request)+ "/wx/api/getWxUserInfo";
        String url = wxMpService.oauth2buildAuthorizationUrl(redirectUri, Constant.OAUTH2_SCOPE_USER_INFO, jumpUrl);
        return "redirect:" + url;
    }

    @RequestMapping("/api/getWxUserInfo")
    public String getWxUserInfo(HttpServletRequest request,HttpServletResponse response) {
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        String upUser = "-1";

        if(state.contains("=")){
            upUser = state.split("=")[1];
        }

        try {
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
            UserInfo userInfo = userInfoService.getUserByOpenId(wxMpUser.getOpenId());
            if(userInfo == null || userInfo.getFlOpenId() == null) {
                userInfo = new UserInfo();
                userInfo.setFlCstId("-1");
                if(!"-1".equalsIgnoreCase(upUser)){
                    UserInfo temp = userInfoService.getById(upUser);
                    userInfo.setFlCstId(temp == null ? "-1":temp.getFlCstId());
                }
                userInfo.setFlIsDis(0);
                userInfo.setFlName(wxMpUser.getNickname());
                userInfo.setFlSex(wxMpUser.getSex());
                userInfo.setFlOpenId(wxMpUser.getOpenId());
                userInfo.setFlAvatar(wxMpUser.getHeadImgUrl());
                userInfo.setFlProvince(wxMpUser.getProvince());
                userInfo.setFlCity(wxMpUser.getCity());
                userInfo.setFlUpUser(upUser);
                userInfoService.save(userInfo);
            }else{
                userInfo.setFlAvatar(wxMpUser.getHeadImgUrl());
                userInfo.setFlLastLoginTime(DateUtil.now());
                userInfo.setFlProvince(wxMpUser.getProvince());
                userInfo.setFlCity(wxMpUser.getCity());
                userInfoService.updateById(userInfo);
            }
            String token = JWTUtil.getToken(userInfo.getFlId(), userInfo.getFlOpenId(), userInfo.getFlName());
            Cookie cookie = new Cookie("token", token);
            cookie.setMaxAge(60 * 60 * 24);// 设置为24H
            cookie.setPath("/");
            response.addCookie(cookie);
            if(state.contains("?")){
                state = state+"&token="+token;
            }else{
                state = state+"?token="+token;
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return "redirect:"+state;
    }

    @GetMapping("/api/getJsApi")
    @ResponseBody
    public R getJsApi(HttpServletRequest request) throws WxErrorException {
        String currentUrl = request.getParameter("url");
        WxJsapiSignature wxJsapiSignature = wxMpService.createJsapiSignature(currentUrl);
        return R.ok(wxJsapiSignature);
    }

    @RequestMapping("/api/payCallback")
    public WxPayNotifyResponse payCallback(@RequestBody String notifyResultXml) throws WxPayException {
        WxPayOrderNotifyResult notifyResult = payService.parseOrderNotifyResult(notifyResultXml);
        WxPayNotifyResponse notifyResponse = orderInfoService.payResultNotify(notifyResult);
        return notifyResponse;
    }

    @RequestMapping("/api/addCookie")
    @ResponseBody
    public R addCookie(HttpServletRequest request,HttpServletResponse response){
        String token = request.getParameter("token");
        Cookie cookie = new Cookie("token", token);
        cookie.setMaxAge(60 * 60 * 24);// 设置为24H
        cookie.setPath("/");
        response.addCookie(cookie);
       return R.ok();
    }
}
